<template>
  <div class="container">
    <el-button type="primary" @click="addShowDialog = true">添加角色</el-button>
    <!-- 数据表格 -->
    <el-table :data="list" border style="width: 100%">
      <!-- 序号 -->
      <el-table-column prop="id" label="序号" width="80">
        <template #default="obj">
          {{ obj.$index + 1 + 5 * (page-1) }}
        </template></el-table-column>
      <!-- 角色 -->
      <el-table-column prop="name" label="角色" width="200">
        <template #default="obj">
          <div v-if="!obj.row.isEdit">{{ obj.row.name }}</div>
          <el-input v-else v-model="obj.row.editRow.name" />
        </template>
      </el-table-column>
      <!-- 启用 -->
      <el-table-column prop="state" label="启用" width="200">
        <template #default="obj">
          <div v-if="!obj.row.isEdit">{{ obj.row.state === 1 ? '已启用' : '未启用' }}</div>
          <el-switch v-else v-model="obj.row.editRow.state" :active-value="1" :inactive-value="0" />
        </template>
      </el-table-column>
      <!-- 描述 -->
      <el-table-column prop="description" label="描述" width="width">
        <template #default="obj">
          <div v-if="!obj.row.isEdit">{{ obj.row.description }}</div>
          <el-input v-else v-model="obj.row.editRow.description" />
        </template></el-table-column>
      <!-- 操作 -->
      <el-table-column fixed="right" label="操作" width="width">
        <template #default="obj">
          <template v-if="!obj.row.isEdit">
            <el-button type="text" size="small" @click="showPermission(obj.row.id)">分配权限</el-button>
            <el-button type="text" size="small" @click="obj.row.isEdit = true">编辑</el-button>
            <el-button type="text" size="small" @click="delDialog=true">
              <el-popconfirm title="这是一段内容确定删除吗？" @onConfirm="deleteRole(obj.row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </el-button>
          </template>
          <template v-else>
            <el-button type="primary" @click="editRole(obj.row)">确定</el-button>
            <el-button type="primary" @click="obj.row.isEdit = false">取消</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页功能 -->
    <el-pagination :page-size="5" layout="prev, pager, next" :total="total" @current-change="updateRoleData" />
    <!-- 分配权限功能 -->
    <el-dialog title="分配权限" :visible.sync="dialogPermission" width="50%">
      <el-tree ref="treeRef" node-key="id" :default-checked-keys="permIds" show-checkbox :check-strictly="true" :data="permissions" :props="{label: 'name'}" default-expand-all :expand-on-click-node="false" />
      <div slot="footer">
        <el-button @click="dialogPermission = false">取 消</el-button>
        <el-button type="primary" @click="onAssignPerm">分配权限</el-button>
      </div>
    </el-dialog>
    <!-- 添加角色 -->
    <el-dialog title="新增角色" :visible.sync="addShowDialog" width="40%">
      <el-form ref="roleForm" label-width="120px" :model="formData" :rules="rules">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="formData.name" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item label="启用">
          <el-switch v-model="formData.state" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="formData.description" type="textarea" :rows="3" style="width:300px" size="mini" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button type="primary" size="mini" @click="addRole">确定</el-button>
              <el-button size="mini">取消</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleListAPI, addRoleAPI, editRoleAPI, deleteRoleAPI, getRoleDetailAPI, assignPermAPI } from '@/api/role'
import { getPermissionListAPI } from '@/api/permission'
import { Message } from 'element-ui'
import { buildTree } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      list: [],
      page: 1,
      pagesize: 5,
      total: 0,
      dialogPermission: false,
      permissions: [],
      addShowDialog: false,
      formData: {
        name: '',
        description: '',
        state: 0 | 1
      },
      delDialog: false,
      rules: {
        name: [{ required: true, message: '角色名称不能为空', trigger: 'blur' }],
        description: [{ required: true, message: '角色描述不能为空', trigger: 'blur' }]
      },
      permIds: []
    }
  },
  // 监听addShowDialog,达到重置表单校验的效果
  watch: {
    addShowDialog(val) {
      if (!val) {
        this.$refs.roleForm.resetFields()
      }
    },
    dialogPermission(val) {
      if (!val) {
        this.$refs.treeRef.setCheckedKeys([])
      }
    }
  },
  created() {
    this.getRoleData()
  },
  updated() {
    this.setList()
  },
  methods: {
    // 获取角色列表
    async getRoleData() {
      const res = await getRoleListAPI({ page: this.page, pagesize: this.pagesize })
      this.list = res.rows
      this.total = res.total
    },
    // 获取权限列表
    async getPermissionList() {
      const res = await getPermissionListAPI()
      this.permissions = buildTree(res)
    },
    // 分页
    async updateRoleData(val) {
      this.page = val
      this.list = []
      await this.getRoleData()
    },
    // 新增角色
    async addRole() {
      await this.$refs.roleForm.validate()
      if (this.isOpen) {
        this.formData.state = 1
      } else {
        this.formData.state = 0
      }
      await addRoleAPI(this.formData)
      Message.success('添加角色成功')
    },
    // 给表单再次增加数据
    setList() {
      this.list.forEach(item => {
        this.$set(item, 'isEdit', false)

        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })
    },
    // 编辑角色
    async editRole(row) {
      if (!row.editRow.name) {
        return Message.warning('角色名称不能为空')
      }
      if (!row.editRow.description) {
        return Message.warning('角色描述不能为空')
      }
      await editRoleAPI({ id: row.id, ...row.editRow })
      Message.success('修改角色成功')
      this.getRoleData()
    },
    // 删除角色
    async deleteRole(id) {
      await deleteRoleAPI(id)
      Message.success('删除角色成功')
      await this.getRoleData()
    },
    // 显示分配权限
    async showPermission(id) {
      await this.getPermissionList()
      const res = await getRoleDetailAPI(id)
      this.permIds = res.permIds
      this.dialogPermission = true
      this.currentId = id
    },
    // 分配权限
    async onAssignPerm() {
      this.permIds = this.$refs.treeRef.getCheckedKeys()
      await assignPermAPI({ id: this.currentId, permIds: this.permIds })
      Message.success('分配权限成功')
      this.dialogPermission = false
    }
  }
}
</script>

<style>
.container{
  background-color: #fff;
}
</style>
